package com.xsd.rabbitmq.work;

import com.rabbitmq.client.*;
import com.xsd.rabbitmq.util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 消费者
 * @Author: zhoufuzong
 * @Created: 2021-03-14 10:37:12
 * @Version: 1.1.0
 */

public class Consumer2 {
    public static void main(String[] args) throws Exception {
        // 获取连接
        Connection connection = ConnectionUtil.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();
        // 创建队列 并设置消息处理
        channel.queueDeclare(Producer.QUEUE_NAME,true,false,false,null);
        // 监听消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /*
           consumerTag: 消息者标签，在channel.basicConcume时可以指定
           envelope: 消息包内容，可从中获取消息id,消息routingkey, 交换机，消息和重转标记（收到消息失败后是否需要重新发送）
           properties: 消息属性
           body:消息
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("");
                System.out.println("========consumer 2 start  =======");
                System.out.println("");
                // 路由key:
                System.out.println("路由key为："+envelope.getRoutingKey());
                System.out.println("交换机："+envelope.getExchange());
                System.out.println("消息id: "+envelope.getDeliveryTag());
                System.out.println("收到的消息："+new String(body,"UTF-8"));
                System.out.println("");
                System.out.println("========consumer 2 end =======");
                System.out.println("");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };


        /*
        监听消息
        参数一：队列名称
        参数二：是否自动确认，设置为true表示消息收到自动向mq回复收到了，mq收到消息后会删除消息；设置false则需要手动确认

         */
        channel.basicConsume(Producer.QUEUE_NAME,true,consumer);


    }
}
